<template>
    <div class="code-edit">
        <el-card class="!border-none" shadow="never">
            <el-page-header content="编辑数据权限" @back="$router.back()" />
        </el-card>
        <el-card class="mt-4 !border-none" shadow="never">
            <el-form ref="formRef" class="ls-form" :model="table_column" label-width="100px" :rules="rules">
                <el-table :data="table_column" row-key="column_name">
                    <!-- <el-table-column label="字段列名" prop="column_name" /> -->
                    <el-table-column label="字段描述" prop="name" min-width="120"></el-table-column>
                    <!-- <el-table-column label="物理类型" prop="column_type" /> -->
                    <el-table-column label="可见" width="80">
                        <template v-slot="{ row }">
                            <el-radio :value="1" v-model="row.radio" @change="boxAdmin"></el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column label="不可见" width="80">
                        <template v-slot="{ row }">
                            <el-radio :value="2" v-model="row.radio" @change="boxAdmin"></el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column label="只读" width="80">
                        <template v-slot="{ row }">
                            <el-radio :value="3" v-model="row.radio" @change="boxAdmin"></el-radio>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
        </el-card>
        <footer-btns>
            <el-button type="primary" @click="onSubmit">保存</el-button>
        </footer-btns>
    </div>
</template>

<script lang="ts" setup name="tableEdit">
import type { FormInstance } from 'element-plus'
import { cloneDeep } from 'lodash'

import { menuAll } from '@/api/perms/menu'
import { roleInfor, formlists, formAdd, formEdit } from '@/api/perms/role'

import { dictTypeAll } from '@/api/setting/dict'
import { generateEdit, tableDetail } from '@/api/tools/code'
import { useDictOptions } from '@/hooks/useDictOptions'
import feedback from '@/utils/feedback'

import useMultipleTabs from '@/hooks/useMultipleTabs'
const { removeTab } = useMultipleTabs()

// import RelationsAdd from '../components/relations-add.vue'

console.log("record")
const route = useRoute()
const router = useRouter()
const activeName = ref('column')
const showEdit = ref(false)
const relationTypes = [
    {
        name: '一对一',
        value: 'has_one'
    },
    {
        name: '一对多',
        value: 'has_many'
    }
]
const table_column = ref([])
const showEdit1 = ref(false)

const formData = reactive({
    id: '',
    table_name: '',
    table_comment: '',
    author: '',
    remark: '',
    template_type: 0,
    generate_type: 0,
    module_name: '',
    class_dir: '',
    class_comment: '',
    table_column: [] as any[],
    menu: {
        pid: 0,
        name: '',
        type: 0
    },
    tree: {
        tree_id: 0,
        tree_pid: 0,
        tree_name: 0
    },
    delete: {
        name: '',
        type: 0
    },
    relations: [] as any[]
})
let editIndex = 0
const formRef = shallowRef<FormInstance>()
// const editRef = shallowRef<InstanceType<typeof RelationsAdd>>()
const rules = reactive({
    table_name: [{ required: true, message: '请输入表名称' }],
    table_comment: [{ required: true, message: '请输入表描述' }],
    module_name: [{ required: true, message: '请输入模块名' }],
    generate_type: [{ required: true, trigger: 'change' }],
    template_type: [{ required: true, trigger: 'change' }],
    ['menu.pid']: [{ required: true, message: '请选择父级菜单' }],
    ['menu.name']: [{ required: true, message: '请输入菜单名称' }],
    ['delete.type']: [{ required: true, trigger: 'change' }],
    ['delete.name']: [{ required: true, message: '请选择删除字段' }]
})

const showEditPopup = async (type: string, data?: any, index?: number) => {
    showEdit.value = true
    await nextTick()
    if (data && index !== undefined) {
        // editRef.value?.setFormData(data)
        editIndex = index
    }
    // editRef.value?.open(type)
}

const handleAdd = (data: any) => {
    const newData = cloneDeep(toRaw(data))
    formData.relations.push(newData)
}

const handleEdit = async (data: any) => {
    const newData = cloneDeep(toRaw(data))
    console.log(editIndex)
    formData.relations.splice(editIndex, 1, newData)
}

const handelDelete = (index: number) => {
    formData.relations.splice(index, 1)
}
const getDetails = async () => {
    const data = await tableDetail({
        id: route.query.id
    })
    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        formData[key] = data[key]
    })

    watch(
        () => formData.generate_type,
        (value) => {
            if (value == 1) {
                feedback
                    .confirm('生成到模块方式如遇同名文件会覆盖旧文件，确定要选择此方式吗？')
                    .catch(() => {
                        formData.generate_type = 0
                    })
            }
        }
    )

}

const boxAdmin = (index: any) => {
    console.log(index, "index")
}
const toRow = (id: any) => {
    // console.log(index, "index")

}


const getlists = async () => {

    table_column.value = await roleInfor()
    const dataObj = await formlists({
        role_id: route.query.id
    })
    console.log(dataObj, "dataObj")
    if (dataObj.column) {
        showEdit1.value = true
        for (let i = 0; i < table_column.value.length; i++) {
            for (let j = 0; j < dataObj.column.length; j++) {
                if (table_column.value[i].column_name == dataObj.column[j].column_name) {
                    table_column.value[i].radio = dataObj.column[j].radio
                }
            }
            // table_column.value[i].radio = dataObj.column[i].radio
            if (!table_column.value[i].radio) {
                table_column.value[i].radio = 1
            }
        }
    } else {
        table_column.value.forEach(ele => {
            ele['radio'] = 1
        })
        showEdit1.value = false
    }

    // if(data.data.length>0){

    // }
    // console.log(data, "data")
    // Object.keys(formData).forEach((key) => {
    //     //@ts-ignore
    //     formData[key] = data[key]
    // })

    // watch(
    //     () => formData.generate_type,
    //     (value) => {
    //         if (value == 1) {
    //             feedback
    //                 .confirm('生成到模块方式如遇同名文件会覆盖旧文件，确定要选择此方式吗？')
    //                 .catch(() => {
    //                     formData.generate_type = 0
    //                 })
    //         }
    //     }
    // )

}
const { optionsData } = useDictOptions<{
    dict_type: any[]
    menu: any[]
}>({
    dict_type: {
        api: dictTypeAll
    },
    menu: {
        api: menuAll,
        transformData(data) {
            const menu = { id: 0, name: '顶级', children: [] }
            menu.children = data
            return [menu]
        }
    }
})

const onSubmit = async () => {

    // console.log(JSON.stringify(table_column.value), "table_column")
    try {
        // await formRef.value?.validate()
        console.log(showEdit1.value, 'showEdit1.value')
        if (showEdit1.value) {
            await formEdit({
                id: route.query.id,
                column: JSON.stringify(table_column.value)
            })
        } else {
            await formAdd({
                role_id: route.query.id,
                column: JSON.stringify(table_column.value)
            })
        }
        removeTab()
        router.back()
    } catch (error: any) {
        for (const err in error) {
            const isInRules = Object.keys(rules).includes(err)
            isInRules && feedback.msgError(error[err][0]?.message)
        }
    }
}

// getDetails()
getlists()
</script>
